
package com.gcloud.mesh.framework.core.init;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import com.gcloud.mesh.framework.core.SpringUtil;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class InitorRunner implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        List<IInitor> initors = new ArrayList<IInitor>(SpringUtil.getBeansOfType(IInitor.class).values());
        Collections.sort(initors, new Comparator<IInitor>() {

            @Override
            public int compare(IInitor o1, IInitor o2) {
                return o1.initPriority().getCode() - o2.initPriority().getCode();
            }
        });
        for (IInitor initor : initors) {
            log.info("[Initor] running {} {}", initor.initPriority().getCode(), initor.getClass().getSimpleName());
            try {
                initor.init();
            }
            catch (Exception e) {
                log.error("[Initor] error: {}", e);
            }
        }
    }

}
